home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9975 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Followup-To: comp.lang.c++,rb.technical
  6. Date: 5 Mar 1996 13:24:21 GMT
  7. Organization: 3M - St. Paul, MN  55144-1000 US
  8. Message-ID: <4hhfa5$m6r@dawn.mmm.com>
  9. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <VA.00000053.00cdab05@fred> <4hdkdj$3id0@news-s01.ny.us.ibm.net>
  10. Reply-To: kjhopps@mmm.com
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. rwolf@ibm.net wrote:
  14. > In <VA.00000053.00cdab05@fred>, Frederic LACHASSE
  15. > <lachass@worldnet.fr> writes:
  16. > >In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com 
  17. > >(Boris Burtin) wrote:
  18. > >> 
  19. > >> I have noticed that a copy constructor and operator= perform pretty
  20. > >> much the same function.  The code I wrote for my class simply copies
  21. > >> each member variable from one class to the other.
  22. > >> 
  23.  
  24. > A rather typical form is to have the create a "ShallowCopy" 
  25. > function that is called from both the copy constructor and the 
  26. > operator=.   ShallowCopy copies only the member variables 
  27. > at the current derivation level.
  28.  
  29. > T::T(const T& t)
  30. > {
  31. >  ShallowCopy(t);
  32. > }
  33.  
  34. > T& operator=(const T& t )
  35. > {
  36. >    if (&t!=this)
  37. >      {
  38. >         ClassReset(); // direct destructor calls are bad form
  39. >         ShallowCopy(t);
  40. >         parentclass::operator=(t);
  41.  
  42. >      }
  43. > return *this;
  44. > }
  45.  
  46.  
  47. > If this form is followed at each level of derivation it will do what
  48. > you want.
  49.  
  50. The ShallowCopy function is not implemented here, but if it functions
  51. as the name implies, a member which points to dynamically allocated
  52. data would be copied by copying the pointer itself, not by creating a
  53. new copy of the original pointed-to data.  This creates a problem with
  54. multiple deletion and dangling pointers as one of the copies is destroyed.
  55. --
  56. Kevin J. Hopps                  e-mail: kjhopps@mmm.com
  57. 3M Company                      phone:  (612) 737-4643
  58. 3M Center, Bldg. 235-2D-57      fax:    (612) 737-2700
  59. St. Paul, MN 55144-1000         Opinions are my own.  I don't speak for 3M.
  60.     But 3M speaks for me -- I did not write the following line:
  61.  
  62. Opinions expressed herein are my own and may not represent those of 3M.
  63.